<?php

/**
 * Initialization Theme
 *
 * @author Vtrois <seaton@vtrois.com>
 * @license GPL-3.0
 * @since 1.0
 */
add_action( 'load-themes.php', 'grace_init_theme' );

function grace_init_theme(){
  global $pagenow;
  if ( 'themes.php' == $pagenow && isset( $_GET['activated'] ) ) {
    wp_redirect( admin_url( 'themes.php?page=grace-theme' ) );
    exit;
  }
}

/**
 * Loads the Options Panel
 *
 * @author Vtrois <seaton@vtrois.com>
 * @license GPL-3.0
 * @since 1.0
 */
if (!function_exists('optionsframework_init')) {
  define('OPTIONS_FRAMEWORK_DIRECTORY', get_template_directory_uri() . '/inc/options/');
  require_once dirname(__FILE__) . '/options/options-framework.php';
  $optionsfile = locate_template( 'options.php' );
  load_template( $optionsfile );
}

add_filter( 'optionsframework_menu', 'grace_options_menu_filter' );

function grace_options_menu_filter( $menu ) {
  $menu['mode'] = 'menu';
  $menu['page_title'] = __( 'Theme Options', 'grace' );
  $menu['menu_title'] = __( 'Theme Options', 'grace' );
  $menu['menu_slug'] = 'grace-theme';
  return $menu;
}

add_action('admin_init','grace_optionscheck_change_santiziation', 100);

function grace_optionscheck_change_santiziation() {
    remove_filter( 'of_sanitize_textarea', 'of_sanitize_textarea' );
    add_filter( 'of_sanitize_textarea', 'grace_custom_sanitize_textarea' );
}
function grace_custom_sanitize_textarea($input) {
    global $allowedposttags;
    $custom_allowedtags["embed"] = array(
        "src" => array(),
        "type" => array(),
        "allowfullscreen" => array(),
        "allowscriptaccess" => array(),
        "height" => array(),
        "width" => array()
      );
    $custom_allowedtags["script"] = array( "type" => array(),"src" => array() );
    $custom_allowedtags = array_merge($custom_allowedtags, $allowedposttags);
    $output = wp_kses( $input, $custom_allowedtags);
    return $output;
}

/**
 * i18n theme languages
 *
 * @author Vtrois <seaton@vtrois.com>
 * @license GPL-3.0
 * @since 1.0
 * @todo Only Chinese and English are currently supported
 */
add_action ('after_setup_theme', 'grace_theme_languages');

function grace_theme_languages(){
  //theme languages
  load_theme_textdomain('grace', get_template_directory() . '/languages');
  //theme option languages(inc/options)
  load_theme_textdomain('theme-textdomain', get_template_directory() . '/languages');
}

/**
 * User list show last login time
 *
 * @author Vtrois <seaton@vtrois.com>
 * @license GPL-3.0
 * @since 1.0
 */
add_action( 'wp_login', 'grace_insert_last_login' );

function grace_insert_last_login( $login ) {
  global $user_id;
  $user = get_userdatabylogin( $login );
  update_user_meta( $user->ID, 'last_login', current_time( 'mysql' ) );
}

add_filter( 'manage_users_columns', 'grace_add_last_login_column' );

function grace_add_last_login_column( $columns ) {
  $columns['last_login'] = __('Last login time' , 'grace');
  return $columns;
}

add_action( 'manage_users_custom_column', 'grace_add_last_login_column_value', 10, 3 );

function grace_add_last_login_column_value( $value, $column_name, $user_id ) {
  $user = get_userdata( $user_id );
  $single = true;
  if ( 'last_login' == $column_name && $user->last_login )
    $value = get_user_meta( $user->ID, 'last_login', $single );
  else $value = __('No record' , 'grace');
  return $value;
}

/**
 * Show id for all thing
 *
 * @author Vtrois <seaton@vtrois.com>
 * @license GPL-3.0
 * @since 1.0
 */
add_action('admin_init', 'grace_ssid_add');

function grace_ssid_column($cols) {
  $cols['ssid'] = 'ID';
  return $cols;
}

function grace_ssid_value($column_name, $id) {
  if ($column_name == 'ssid')
    echo $id;
}
 
function grace_ssid_return_value($value, $column_name, $id) {
  if ($column_name == 'ssid')
    $value = $id;
  return $value;
}

function grace_ssid_css() {
?>
<style type="text/css">
  #ssid { width: 50px; }
</style>
<?php 
}

function grace_ssid_add() {
  add_action('admin_head', 'grace_ssid_css');
 
  add_filter('manage_posts_columns', 'grace_ssid_column');
  add_action('manage_posts_custom_column', 'grace_ssid_value', 10, 2);
 
  add_filter('manage_pages_columns', 'grace_ssid_column');
  add_action('manage_pages_custom_column', 'grace_ssid_value', 10, 2);
 
  add_filter('manage_media_columns', 'grace_ssid_column');
  add_action('manage_media_custom_column', 'grace_ssid_value', 10, 2);
 
  add_filter('manage_link-manager_columns', 'grace_ssid_column');
  add_action('manage_link_custom_column', 'grace_ssid_value', 10, 2);
 
  add_action('manage_edit-link-categories_columns', 'grace_ssid_column');
  add_filter('manage_link_categories_custom_column', 'grace_ssid_return_value', 10, 3);
 
  foreach ( get_taxonomies() as $taxonomy ) {
    add_action("manage_edit-${taxonomy}_columns", 'grace_ssid_column');     
    add_filter("manage_${taxonomy}_custom_column", 'grace_ssid_return_value', 10, 3);
  }
 
  add_action('manage_users_columns', 'grace_ssid_column');
  add_filter('manage_users_custom_column', 'grace_ssid_return_value', 10, 3);
 
  add_action('manage_edit-comments_columns', 'grace_ssid_column');
  add_action('manage_comments_custom_column', 'grace_ssid_value', 10, 2);
}

/**
 * Loading theme resources
 *
 * @author Vtrois <seaton@vtrois.com>
 * @license GPL-3.0
 * @since 1.0
 */
add_action('wp_enqueue_scripts', 'grace_theme_scripts');

function grace_theme_scripts() {  
  $dir = get_template_directory_uri();

  //css
  wp_enqueue_style( 'bootstrap', $dir . '/static/css/bootstrap.min.css', array(), GRACE_VERSION);
  wp_enqueue_style( 'font-awesome', $dir . '/static/css/font-awesome.min.css', array(), GRACE_VERSION);
  wp_enqueue_style( 'animate', $dir . '/static/css/animate.min.css', array(), GRACE_VERSION);
wp_enqueue_style( 'layer', $dir . '/static/css/layer.min.css', array(), GRACE_VERSION);
  wp_enqueue_style( 'flexslider', $dir . '/static/css/flexslider.min.css', array(), GRACE_VERSION);
//wp_enqueue_style( 'layui', $dir . '/static/layui/css/layui.css', array(), GRACE_VERSION);
  wp_enqueue_style( 'grace', $dir . '/static/css/grace.css', array(), GRACE_VERSION);

  //javascript
  wp_enqueue_script( 'jquery', $dir . '/static/js/jquery.min.js' , array(), GRACE_VERSION);
  wp_enqueue_script( 'bootstrap', $dir . '/static/js/bootstrap.min.js' , array(), GRACE_VERSION);  
  wp_enqueue_script( 'easing', $dir . '/static/js/jquery.easing.min.js', array(), GRACE_VERSION);
  wp_enqueue_script( 'flexslider', $dir . '/static/js/jquery.flexslider.min.js', array(), GRACE_VERSION);
  wp_enqueue_script( 'sticky', $dir . '/static/js/sticky.min.js', array(), GRACE_VERSION);
  wp_enqueue_script( 'wow', $dir . '/static/js/wow.min.js', array(), GRACE_VERSION);
wp_enqueue_script( 'layer', $dir . '/static/js/layer.min.js', array(), GRACE_VERSION);
//wp_enqueue_script( 'layui', $dir . '/static/layui/layui.js', array(), GRACE_VERSION);
  wp_enqueue_script( 'main', $dir . '/static/js/main.js', array(), GRACE_VERSION);

  if (is_singular()) {
    wp_enqueue_style( 'highlight', $dir . '/static/css/highlight.min.css', array(), GRACE_VERSION);
    wp_enqueue_script( 'qrcode', $dir . '/static/js/jquery.qrcode.min.js', array(), GRACE_VERSION);
    wp_enqueue_script( 'highlight', $dir . '/static/js/highlight.min.js', array(), GRACE_VERSION);
    wp_enqueue_script( 'share', $dir . '/static/js/share.min.js', array(), GRACE_VERSION);
  }

  $datatoGrace = array(
    'site' => home_url(),
    'directory' => get_stylesheet_directory_uri(),
    'alipay' => grace_option('donate_alipay_qr'),
    'wechat' => grace_option('donate_wechat_qr'),
    'copyright' => grace_option('single_copyright'),
    'more' => __('Load More' , 'grace'),
    'repeat' => __('You are already supported it' , 'grace'),
    'thanks' => __('Thank you for your support' , 'grace'),
    'donate' => __('Donate to author' , 'grace'),
    'scan' => __('Scan payment' , 'grace'),
    'article_img_type' => grace_option('article_img_type'),
  );
  wp_localize_script( 'main', 'v3', $datatoGrace );
}

/**
 * Replace the jquery resources
 *
 * @author Vtrois <seaton@vtrois.com>
 * @license GPL-3.0
 * @since 1.0
 */
add_action( 'wp_enqueue_scripts', 'grace_enqueue_scripts', 1 );

function grace_enqueue_scripts() {
  wp_deregister_script('jquery');
}

/**
 * Enable links
 *
 * @author Vtrois <seaton@vtrois.com>
 * @license GPL-3.0
 * @since 1.0
 */
add_filter( 'pre_option_link_manager_enabled', '__return_true' );

/**
 * Optimized built-in functions
 *
 * @author Vtrois <seaton@vtrois.com>
 * @license GPL-3.0
 * @since 1.0
 */
add_filter( 'emoji_svg_url', '__return_false' );
add_filter( 'show_admin_bar', '__return_false' );
remove_action( 'wp_head', 'wp_print_head_scripts', 9 );
remove_action( 'wp_head', 'wp_generator' );
remove_action( 'wp_head', 'rsd_link' );
remove_action( 'wp_head', 'wlwmanifest_link' );
remove_action( 'wp_head', 'index_rel_link' );
remove_action( 'wp_head', 'parent_post_rel_link', 10, 0 );
remove_action( 'wp_head', 'start_post_rel_link', 10, 0 );
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );
remove_action( 'wp_head', 'rel_canonical' );
remove_action( 'wp_head', 'feed_links', 2 );
remove_action( 'wp_head', 'feed_links_extra', 3 );
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('admin_print_styles', 'print_emoji_styles');
remove_filter('the_content', 'wptexturize'); 
remove_filter('comment_text', 'wptexturize');
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
remove_action('embed_head', 'print_emoji_detection_script');
remove_filter('the_content_feed', 'wp_staticize_emoji');
remove_filter('comment_text_rss', 'wp_staticize_emoji');
remove_filter('wp_mail', 'wp_staticize_emoji_for_email');

/**
 * Disable open sans
 *
 * @author Vtrois <seaton@vtrois.com>
 * @license GPL-3.0
 * @since 1.0
 */
add_filter('gettext_with_context', 'grace_disable_open_sans', 888, 4 );

function grace_disable_open_sans( $translations, $text, $context, $domain )
{
    if ( 'Open Sans font: on or off' == $context && 'on' == $text ) {
        $translations = 'off';
    }
    return $translations;
}

/**
 * Replace the default avatar server
 *
 * @author Vtrois <seaton@vtrois.com>
 * @license GPL-3.0
 * @since 1.0
 */
add_filter( 'get_avatar', 'grace_get_avatar' );

function grace_get_avatar( $avatar ) {
  $avatar = str_replace( array( 'www.gravatar.com', '0.gravatar.com', '1.gravatar.com', '2.gravatar.com', '3.gravatar.com', 'secure.gravatar.com' ), 'cn.gravatar.com', $avatar );
  return $avatar;
}

/**
 * Support webP file upload
 *
 * @author Vtrois <seaton@vtrois.com>
 * @license GPL-3.0
 * @since 1.0
 */
add_filter('upload_mimes','grace_upload_webp');

function grace_upload_webp ( $existing_mimes=array() ) {
  $existing_mimes['webp']='image/webp';
  return $existing_mimes;
}

/**
 * The welcome panel notice
 *
 * @author Vtrois <seaton@vtrois.com>
 * @license GPL-3.0
 * @since 1.0
 */
add_action( 'welcome_panel', 'grace_welcome_notice' );

function grace_welcome_notice() {
  ?>
  <style type="text/css">
    .about-description a{
      text-decoration:none;
    }
  </style>
  <div class="notice notice-info">
  <p class="about-description"><?php echo '欢迎使用 <a href="https://gitee.com/rgq0503/Grace.git" target="_blank">Grace 主题 </a> 来进行创作，本主题基于主题 <a target="_blank" rel="nofollow" href="https://www.vtrois.com/theme-dobby.html"> Dobby </a>进行改造开发，在开始使用主题前查看主题<a href="https://gitee.com/rgq0503/Grace/wikis" target="_blank">使用介绍</a>，如果您遇到了某些错误，欢迎来咨询， <a target="_blank" rel="nofollow" href="https://gitee.com/rgq0503/Grace/issues/new">提交错误</a>。';?></p></div>
  <?php
}

/*个人资料中添加用户额外信息*/
add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );
function extra_user_profile_fields( $user ) { ?>
<h3>用户额外信息</h3>
<table class="form-table">
    <tr>
        <th><label for="qq_qr">QQ二维码</label></th>
        <td>
            <input type="text" name="qq_qr" id="qq_qr" value="<?php echo esc_attr( get_the_author_meta( 'qq_qr', $user->ID ) ); ?>" class="regular-text" />
            <label class="regular-text" >请在媒体资源中上传二维码图片(建议200px*200px)，并且复制url地址到这里。（投稿者请联系管理员上传）</label>
        </td>
    </tr>
    <tr>
        <th><label for="wechat_qr">微信二维码</label></th>
        <td>
            <input type="text" name="wechat_qr" id="wechat_qr" value="<?php echo esc_attr( get_the_author_meta( 'wechat_qr', $user->ID ) ); ?>" class="regular-text" />
            <label class="regular-text" >请在媒体资源中上传二维码图片(建议200px*200px)，并且复制url地址到这里。（投稿者请联系管理员上传）</label>
        </td>
    </tr>
    <tr>
        <th><label for="weibo">新浪微博地址</label></th>
        <td>
            <input type="text" name="weibo" id="weibo" value="<?php echo esc_attr( get_the_author_meta( 'weibo', $user->ID ) ); ?>" class="regular-text" />
        </td>
    </tr>
    <tr>
        <th><label for="alipay_qr">支付宝收款二维码</label></th>
        <td>
            <input type="text" name="alipay_qr" id="alipay_qr" value="<?php echo esc_attr( get_the_author_meta( 'alipay_qr', $user->ID ) ); ?>" class="regular-text" />
           <label class="regular-text" >请在媒体资源中上传二维码图片(建议200px*200px)，并且复制url地址到这里。（投稿者请联系管理员上传）</label>
        </td>
    </tr>
    <tr>
        <th><label for="wechatpay_qr">微信收款二维码</label></th>
        <td>
            <input type="text" name="wechatpay_qr" id="wechatpay_qr" value="<?php echo esc_attr( get_the_author_meta( 'wechatpay_qr', $user->ID ) ); ?>" class="regular-text" />
            <label class="regular-text" >请在媒体资源中上传二维码图片(建议200px*200px)，并且复制url地址到这里。（投稿者请联系管理员上传）</label>
        </td>
    </tr>    
</table>
<?php }
add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );
function save_extra_user_profile_fields( $user_id ) {
    if ( !current_user_can( 'edit_user', $user_id ) ) { return false; }
    update_usermeta( $user_id, 'qq_qr', $_POST['qq_qr'] );
    update_usermeta( $user_id, 'wechat_qr', $_POST['wechat_qr'] );
    update_usermeta( $user_id, 'weibo', $_POST['weibo'] );
    update_usermeta( $user_id, 'alipay_qr', $_POST['alipay_qr'] );
    update_usermeta( $user_id, 'wechatpay_qr', $_POST['wechatpay_qr'] );
}

/*打开媒体文件上传路径设置*/
if(get_option('upload_path')=='wp-content/uploads' || get_option('upload_path')==null) 
{
    update_option('upload_path',WP_CONTENT_DIR.'/uploads');
}

/**
 * WordPress 媒体库显示文件的链接地址
 */
add_filter( 'manage_media_columns', 'wpdaxue_media_column' );
function wpdaxue_media_column( $columns ) {
	$columns["media_url"] = "URL";
	return $columns;
}
add_action( 'manage_media_custom_column', 'wpdaxue_media_value', 10, 2 );
function wpdaxue_media_value( $column_name, $id ) {
	if ( $column_name == "media_url" ) echo '<input type="text" width="100%" onclick="jQuery(this).select();" value="'. wp_get_attachment_url( $id ). '" />';
}

/**
 * WordPress 后台媒体库显示文件的链接地址，操作功能项目那里添加url显示
 */
add_filter( 'media_row_actions', 'wpdaxue_media_row_actions', 10, 2 );
function wpdaxue_media_row_actions( $actions, $object ) {
	$actions['url'] = '<a href="'.wp_get_attachment_url( $object->ID ).'" target="_blank">URL</a>';
	return $actions;
}

/**
 * WordPress 媒体库只显示用户自己上传的文件
 * https://www.wpdaxue.com/view-user-own-media-only.html
 */
//在文章编辑页面的[添加媒体]只显示用户自己上传的文件
function my_upload_media( $wp_query_obj ) {
	global $current_user, $pagenow;
	if( !is_a( $current_user, 'WP_User') )
		return;
	if( 'admin-ajax.php' != $pagenow || $_REQUEST['action'] != 'query-attachments' )
		return;
	if( !current_user_can( 'manage_options' ) && !current_user_can('manage_media_library') )
		$wp_query_obj->set('author', $current_user->ID );
	return;
}
add_action('pre_get_posts','my_upload_media');
   
//在[媒体库]只显示用户上传的文件
function my_media_library( $wp_query ) {
    if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/upload.php' ) !== false ) {
        if ( !current_user_can( 'manage_options' ) && !current_user_can( 'manage_media_library' ) ) {
            global $current_user;
            $wp_query->set( 'author', $current_user->id );
        }
    }
}
add_filter('parse_query', 'my_media_library' );


/**
 * 修改url重写后的作者存档页的链接变量
 * @since yundanran-3 beta 2
 * 2013年10月8日23:23:49
 */
add_filter( 'author_link', 'yundanran_author_link', 10, 2 );
function yundanran_author_link( $link, $author_id) {
    global $wp_rewrite;
    $author_id = (int) $author_id;
    $link = $wp_rewrite->get_author_permastruct();
 
    if ( empty($link) ) {
        $file = home_url( '/' );
        $link = $file . '?author=' . $author_id;
    } else {
        $link = str_replace('%author%', $author_id, $link);
        $link = home_url( user_trailingslashit( $link ) );
    }
 
    return $link;
}

/**
 * 替换作者的存档页的用户名，防止被其他用途
 * 作者存档页链接有2个查询变量，
 * 一个是author（作者用户id），用于未url重写
 * 另一个是author_name（作者用户名），用于url重写
 * 此处做的是，在url重写之后，把author_name替换为author
 * @version 1.0
 * @since yundanran-3 beta 2
 * 2013年10月8日23:19:13
 * @link https://www.wpdaxue.com/use-nickname-for-author-slug.html
 */
 
add_filter( 'request', 'yundanran_author_link_request' );
function yundanran_author_link_request( $query_vars ) {
    if ( array_key_exists( 'author_name', $query_vars ) ) {
        global $wpdb;
        $author_id=$query_vars['author_name'];
        if ( $author_id ) {
            $query_vars['author'] = $author_id;
            unset( $query_vars['author_name'] );    
        }
    }
    return $query_vars;
}

/*开启自定义编辑器*/
add_filter('use_block_editor_for_post', '__return_false');

/**
  *WordPress 自定义文章编辑器的样式
  *自定义 CSS 文件
  *http://www.endskin.com/editor-style/
*//*
function Bing_add_editor_style(){
  add_editor_style( get_template_directory_uri().'/static/css/grace.css' );//这样就会调用主题目录 CSS 文件夹的 custom-editor-style.css 文件
}
add_action( 'after_setup_theme', 'Bing_add_editor_style' );*/